import logging

# === 方案二：使用LogRecord工厂函数探测logger名称 ===
# 存储检测到的logger名称
detected_logger_names = set()


def custom_log_record_factory(*args, **kwargs):
    """自定义LogRecord工厂函数"""
    record = logging.getLogRecordFactory()(*args, **kwargs)
    # 记录logger名称
    detected_logger_names.add(record.name)
    return record


def start_logger_detection():
    """开始logger检测"""
    # 保存原始工厂函数
    original_factory = logging.getLogRecordFactory()
    # 设置自定义工厂函数
    logging.setLogRecordFactory(custom_log_record_factory)
    return original_factory


def stop_logger_detection(original_factory):
    """停止logger检测并恢复原始设置"""
    logging.setLogRecordFactory(original_factory)


def get_detected_loggers():
    """获取检测到的logger名称"""
    return sorted(list(detected_logger_names))


# 使用示例
if __name__ == "__main__":
    # 开始检测
    original_factory = start_logger_detection()

    # 在这里导入并使用你的第三方库
    # 示例：
    import urllib3

    http = urllib3.PoolManager()
    response = http.request('GET', 'https://www.baidu.com')

    # 打印检测到的logger名称
    print("通过LogRecord工厂函数检测到的logger名称:")
    for name in get_detected_loggers():
        print(f"  {name}")

    # 恢复原始设置
    stop_logger_detection(original_factory)
